<template>
  <div class="controls">
    <input
      autocomplete="off"
      class="itxt"
      :value="currentValue"
      @blur="handleInputBlur"
    />
    <button
      class="plus"
      @click="setCurrentValue(1)"
      :disabled="currentValue === max"
    >
      +
    </button>
    <button
      class="mins"
      @click="setCurrentValue(-1)"
      :disabled="currentValue === min"
    >
      -
    </button>
  </div>
</template>

<script>
/*
  1. 有最小值和最大值
  2. 输入小于最小值，等于最小值
  3. 输入大于最大值，等于最大值
  4. 输入小数，取整
  5. 输入非数字，变成之前的值
*/
export default {
  name: "InputNumber",
  props: {
    min: {
      type: Number,
      default: 1,
    },
    max: {
      type: Number,
      default: 10,
    },
    value: {
      type: Number,
      default: 1,
    },
  },
  data() {
    return {
      currentValue: this.value,
    };
  },
  methods: {
    setCurrentValue(val) {
      this.currentValue += val;
    },
    handleInputBlur(e) {
      this.currentValue = e.target.value;
    },
  },
  watch: {
    currentValue(newVal, oldVal) {
      const { min, max } = this;
      // 输入小数，取整
      let value = Math.round(newVal);
      // 输入小于最小值，等于最小值
      if (value < min) value = min;
      // 输入大于最大值，等于最大值
      if (value > max) value = max;
      // 输入非数字，变成之前的值
      if (Number.isNaN(value)) {
        value = oldVal;
      }
      // 更新currentValue的值
      this.currentValue = value;

      this.$emit("input", value);
    },
  },
};
</script>

<style lang="less" scoped>
.controls {
  width: 55px;
  position: relative;
  float: left;
  margin-right: 15px;

  .itxt {
    width: 39px;
    height: 38px;
    border: 1px solid #ddd;
    color: #555;
    float: left;
    border-right: 0;
    text-align: center;
    outline: none;
  }

  .plus,
  .mins {
    width: 15px;
    text-align: center;
    height: 20px;
    line-height: 17px;
    background: #f1f1f1;
    color: #666;
    right: 0;
    position: absolute;
    border: 1px solid #ccc;
    cursor: pointer;
    &:disabled {
      color: #ccc;
      cursor: not-allowed;
    }
  }

  .mins {
    top: 20px;
    border-top: 0;
  }
}
</style>
